package com.yj.springbootelasticsearch.rest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class TestController {


    @Resource
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    RestHighLevelClient restHighLevelClient;

    @Resource
    ObjectMapper objectMapper;

    @GetMapping("test")
    public MyShop test() throws IOException {
        MyShop myshop = elasticsearchRestTemplate.get("1", MyShop.class, IndexCoordinates.of("myshop"));
        GetRequest getRequest = new GetRequest();
        getRequest.index("myshop");
        getRequest.id("1");

        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields);
        Map<String, DocumentField> fields = documentFields.getFields();
        System.out.println(fields);
        return myshop;
    }

    /**
     * 往es 索引中添加一条数据
     * @return
     * @throws IOException
     */
    @GetMapping("add")
    public IndexResponse insert() throws IOException {
        MyShop myShop = new MyShop();
        myShop.setId(100);
        myShop.setName("测试");
        myShop.setDesc("这是一条测试数据！");
        String value = objectMapper.writeValueAsString(myShop);

        IndexRequest indexRequest = new IndexRequest("myshop");
        indexRequest.source(value, XContentType.JSON);

        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        return indexResponse;
    }

    /**
     * 创建索引
     */
    @GetMapping("create")
    public void create(){
        IndexRequest indexRequest = new IndexRequest("info").create(true);

    }

}



@Data
class MyShop{
    private Integer id;
    private String name;
    private String desc;
}